package com.yuwei.yurpc.serializer;

import java.io.*;

/**
 * JDK 序列化器
 *
 * @author yuwei
 * @date 13:20 2024/10/3
 */
public class JdkSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
        objectOutputStream.writeObject(obj);
        objectOutputStream.close();
        return out.toByteArray();
    };
    @Override
    public <T> T deserialize(byte[] bytes,Class<T> type) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(in);
        try {
            return (T)objectInputStream.readObject();
        }catch(ClassNotFoundException e){
            throw new RuntimeException(e);
        }finally {
            objectInputStream.close();
        }
    }
}
